package com.ytktt.study.week8.task6.shardingsphere.atomikosxa.service.impl;

import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.entity.item.ItemStockEntity;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.entity.order.OrderInfoEntity;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.mapper.order.OrderInfoMapper;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.service.ItemService;
import com.ytktt.study.week8.task6.shardingsphere.atomikosxa.service.OrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单服务业务逻辑实现
 *
 * @author ytk
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderInfoMapper orderInfoMapper;
    private final ItemService itemService;

    /**
     * TODO 简单实现逻辑测试分布式事务
     * @param orderInfoEntity the order info entity
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @ShardingSphereTransactionType(TransactionType.XA)
    public void createOrder(OrderInfoEntity orderInfoEntity) {
        ItemStockEntity itemStock = this.itemService.getItemStock(orderInfoEntity.getItemId());
        if (itemStock.getStock() >= orderInfoEntity.getAmount()) {
            boolean result = this.itemService.decreItemStock(orderInfoEntity.getItemId(), orderInfoEntity.getAmount());
            if (result) {
                this.orderInfoMapper.insertSelective(orderInfoEntity);
                orderInfoEntity.setAmount(Integer.valueOf("str"));
                System.out.println(orderInfoEntity);
            }
        }
    }
}
